import cookie from 'js-cookie';

type StorageType = 'localStorage' | 'sessionStorage' | 'cookie';
type TokenKeyType = 'list' | 'user';
let storage: StorageType;
const tokenTableName: TokenKeyType = 'list';

const accessToken = {
  get(key: TokenKeyType) {
    key = key || tokenTableName;
    if (key && storage) {
      switch (storage) {
        case 'sessionStorage':
          return sessionStorage.getItem(key);
        case 'cookie':
          return cookie.get(key);
        default:
          return localStorage.getItem(key);
      }
    }
    return null;
  },
  set(key: TokenKeyType, val: any) {
    key = key || tokenTableName;
    if (key && storage) {
      switch (storage) {
        case 'sessionStorage':
          return sessionStorage.setItem(key, val);
        case 'cookie':
          return cookie.set(key, val);
        default:
          return localStorage.setItem(key, val);
      }
    }
    return false;
  },
  remove(key: TokenKeyType) {
    key = key || tokenTableName;
    if (key && storage) {
      switch (storage) {
        case 'sessionStorage':
          return sessionStorage.removeItem(key);
        case 'cookie':
          return cookie.remove(key);
        default:
          return localStorage.removeItem(key);
      }
    }
    return false;
  },
  clear() {
    if (storage) {
      switch (storage) {
        case 'sessionStorage':
          return sessionStorage.clear();
        default:
          return localStorage.clear();
      }
    }

    return true;
  },
};

export default accessToken;
